﻿using BaseAuthRole.Domain.Input;
using BaseAuthRole.Domain.OutPut;
using BaseAuthRole.IService;
using log4net;
using log4net.Repository.Hierarchy;
using Lotus.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using RS.BaseModel;
using RS.BaseModel.Common;
using RS.Environment;
using RS.Tool.Base;
using RS.Tool.Init;

namespace BaseAuthRole.Web.Controllers
{
    [Route("[controller]/[action]")]
    public class ThirdPartyOAuthController : Controller
    {
        private string client_id = ConfigurationHelper.GetAppSettings("TDoauthClientId");
        private string client_secret = ConfigurationHelper.GetAppSettings("TDoauthClientSecret");
        private string grant_type = "authorization_code";
        private string authTokenApi = ConfigurationHelper.GetAppSettings("TDoauthApiUrl");
        private string userInfoApi = ConfigurationHelper.GetAppSettings("TDUserApiUrl");
        private string redirect_uri = ConfigurationHelper.GetAppSettings("TDRedirectUrl");
        private IUserService _userService;
        ILog logger= log4net.LogManager.GetLogger("ThirdPartyOAuthController");


        private IBaseLotusClient _baseLotusClient;

        public ThirdPartyOAuthController(IUserService userService, IBaseLotusClient baseLotusClient) { 
        
           this._userService= userService;
           this._baseLotusClient= baseLotusClient;
        }

        [HttpPost]
        public string Test([FromForm] BaseUserInputModel baseUserInputModel)
        {
            return JsonConvert.SerializeObject(baseUserInputModel);
        }

        
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IActionResult LTSCode() {

            var auth_code=Request.Query["code"].ToString();

            var return_url = Request.Query["return_url"].ToString();

            var appid = Request.Query["appid"].ToString();

            var authTokenPara=new Dictionary<string, string>();

            authTokenPara.Add("client_id", client_id);
            authTokenPara.Add("client_secret", client_secret);
            authTokenPara.Add("grant_type", grant_type);
            authTokenPara.Add("redirect_uri", redirect_uri);
            authTokenPara.Add("code", auth_code);

            var authToken_r = "";

            try
            {
                authToken_r = HttpHelper.Post(authTokenApi, null, authTokenPara, "123456789", "utf-8");
                logger.Info(authToken_r);
            }
            catch (Exception ex) {

                logger.Error("authToken_r");
                logger.Error(ex.Message);
            }
            var authToken = JsonConvert.DeserializeObject<LTSOAuthTokenOutPut>(authToken_r);

            if (authToken==null||string.IsNullOrEmpty(authToken.access_token))
            {

                ViewData["message"] = "token获取失败";

                return PartialView();
            }

            var user_r = "";
            try
            {
                user_r = HttpHelper.Get(userInfoApi + $"?access_token={authToken.access_token}");

                logger.Info("user_r");
                logger.Info(JsonConvert.SerializeObject(user_r));

            }
            catch (Exception ex)
            {
                logger.Error("user_r");
                logger.Error(ex.Message);
            }
            var user= JsonConvert.DeserializeObject<LTSUserOutPut>(user_r);

            if (user==null||string.IsNullOrEmpty(user.employeeNumber))
            {

                ViewData["message"] = "user获取失败";

                return PartialView();
            }

            //检查是否新用户

            var local_user_r = this._userService.GetUserInfoByJobNumber(new Domain.Input.GetUserInfoByJobNumberInput 
            {
                AppAccessToken = "0",
                AppId = "0",
                Id = "0",
                JobNumber = user.employeeNumber
            });


            var Uid = "";
            //不存在用户
            if (local_user_r.IsError)
            {
                var info = _baseLotusClient.GetLotusUserInfoList(new Lotus.Domain.Input.Lotus.GetLotusUserInfoListInput
                {
                    PageNo = 1,
                    PageSize = 100,
                    EmpNos = new List<string>() { user.employeeNumber }
                });
                if (!info.IsError)
                {
                    if (info.Result.Data.DataList.Count > 0)
                    {
                        var temp = info.Result.Data.DataList.Where(p => p.EmployeeTypeCode != "98" && p.State != null && p.Gender != null).ToList().Select(o => new AddOrUpdateUserInput
                        {
                            Id=o.UserId,
                            Name=o.Name,
                            LoginName=o.UserName,
                            Picture=o.Picture,
                            Phone=o.Mobile,
                            JobNumber=o.EmployeeNo,
                            NickName=o.NickName,
                            Department=o.DeptName,
                            DepartmentId=o.DeptId,
                            JobTitle=o.JobTitle,
                            JobState=o.State.Value,
                            Email=o.Email,
                            IdCardNo=o.IdCardNo,
                            NationalityCode=o.NationalityCode,
                            Nationality=o.Nationality,
                            Gender=o.Gender.Value,
                            TopQualifications=o.TopQualifications,
                            Nation=o.Nation,
                            NationPlace=o.NationPlace,
                            EmployeeType=o.EmployeeTypeCode,
                            CompanyAge=o.CompanyAge,
                            PositionName=o.PositionName,
                            JobLevel=o.JobLevel,
                            StaffSystem=o.StaffSystem,
                            StaffSystemCode=o.StaffSystemCode,
                            BirthDate=o.BirthDate,
                            FSUnionId=o.FSUnionId,
                            ExtFSUnionId=o.ExtFsUnionId,
                            Company=o.Company,
                            CompanyNo=o.CompanyNo,
                            Managerid = o.ManagerId,
                        }).ToList();

                        if (temp.Count > 0)
                        {
                            Uid = temp.First().Id;
                            _userService.AddOrUpdateUser(temp);
                        }
                    }
                }
                else
                {
                    ViewData["message"] = "user获取失败";

                    return PartialView();
                }

                //不存在用户
                //var temp = new DTO.User.UUIUser
                //{
                //    Id=user.uid,
                //    JobNumber = user.employeeNumber,
                //    Name = user.realname,
                //    LoginName = user.username,
                //    Department = user.department,
                //    JobTitle = user.title,
                //    NickName = user.user,
                //    Phone = user.mobile,
                //    PassWord = SecretHelper.GetMD5(user.mobile),
                //    BirthDate=user.birthday,
                //    Gender = user.gender==null?3:user.gender.Value
                //};

                //var temp= new AddOrUpdateUserInput
                //{
                //    Id = o.UserId,
                //    Name = o.Name,
                //    LoginName = o.UserName,
                //    Picture = o.Picture,
                //    Phone = o.Mobile,
                //    JobNumber = o.EmployeeNo,
                //    NickName = o.NickName,
                //    Department = o.DeptName,
                //    DepartmentId = o.DeptId,
                //    JobTitle = o.JobTitle,
                //    JobState = o.State,
                //    Email = o.Email,
                //    IdCardNo = o.IdCardNo,
                //    NationalityCode = o.NationalityCode,
                //    Nationality = o.Nationality,
                //    Gender = o.Gender,
                //    TopQualifications = o.TopQualifications,
                //    Nation = o.Nation,
                //    NationPlace = o.NationPlace,
                //    EmployeeType = o.EmployeeTypeCode,
                //    CompanyAge = o.CompanyAge,
                //    PositionName = o.PositionName,
                //    JobLevel = o.JobLevel,
                //    StaffSystem = o.StaffSystem,
                //    StaffSystemCode = o.StaffSystemCode,
                //    BirthDate = o.BirthDate,
                //    FSUnionId = o.FSUnionId,
                //};

                //创建用户
                //this._userService.AddUUIUser(temp);

                //Uid = temp.Id;
            }
            else {

                Uid = local_user_r.Result.Uid;
            }
            //登录用户
            var login_user_model = new BaseUserLoginModel
            {
                Id =Uid,
                Name = user.realname,
                Token = "",
            };

            //UserCookieHelper.SetCookieUserInfo(login_user_model, DateTimeOffset.Now.AddHours(2));

            //开始授权
            var auth_r = this._userService.GetUserAuthCode(appid, Uid, "auth_base", return_url);

            if (auth_r.IsError)
            {

                ViewData["message"] = auth_r.Message;

                return PartialView();
            }
            else
            {

                if (return_url.Contains("?"))
                {
                    return_url += "&auth_code=" + auth_r.Result;
                }
                else
                {
                    return_url += "?auth_code=" + auth_r.Result;
                }

            return Redirect(return_url); 

            }

            return PartialView();

        }
    }
}
